<?php

namespace app\common\service\supplier;

use app\common\facade\auth\Auth;
use app\common\service\auth\AuthApiService;
use app\common\service\auth\AuthYmshService;
use app\model\BaseSupplier;
use app\model\CouponOrder;
use think\Exception;

/**
 * 只用于前端
 */
class SupplierService
{


    /**
     * @var BaseSupplier $baseSupplier
     */
    public $baseSupplier;

    /**
     * 配置模式
     * @param $serv_type
     * @return $this|void
     * @throws Exception
     */
    public function init($serv_type)
    {

        $key = array_search($serv_type, BaseSupplier::CODE_PRODUCT);

        $auth = Auth::instance();

        $codeTrs = [
            PRODUCT_SECKILL_SERV => 'meituan_union',//分销联盟
            PRODUCT_METUAN_SERV => 'meituan_union',//分销联盟
            PRODUCT_MEITUAN_TAKEOUT_SERV => 'meituan_pub',//美团外卖
        ];

        //如果是h5请求,就查找当前渠道的代理商有没有接口模式，agent_id 有值
        if ($auth instanceof AuthApiService) {
            $baseSupplier = BaseSupplier::query()
                ->where('serv_type', $serv_type)
                ->where('agent_id', Auth::agentId())
                ->where('code', $codeTrs[$serv_type]??'===')
//                ->cache('AuthApiServicebaseSupplier' . $serv_type . $key . Auth::agentId())
                ->find();

            if ($baseSupplier) {
                $this->baseSupplier = $baseSupplier;
                return $this;
            }
        }

        if (empty($key)) {
            return;
        }

        $this->baseSupplier = BaseSupplier::query()
            ->where('serv_type', $serv_type)
            ->where('code', $key)
            ->where('agent_id', 0)
            ->findOrEmpty();

        if (!$this->baseSupplier) {
            throw new Exception('缺少供应商配置');
        }

        return $this;

    }

    /**
     * 秘钥
     */
    public function getAppkey()
    {
        return $this->baseSupplier->api_config['apikey'] ?? '';
    }

    /**
     * 秘钥
     */
    public function getSecret()
    {
        return $this->baseSupplier->api_config['secret'] ?? '';
    }


    /**
     * 获取utm 资源
     * @return string
     */
    public function getUtmSource()
    {
        return $this->baseSupplier->api_config['utmSource'] ?? '';
    }

    /**
     * getPromotionId
     * @return string
     */
    public function getPromotionId()
    {
        return $this->baseSupplier->api_config['promotionId'] ?? '';
    }

    /**
     * 获取供应商
     * @return BaseSupplier
     */
    public function getBaseSupplier()
    {
        return $this->baseSupplier;
    }


}